import qiniu from "qiniu";
import { Service } from "typedi";
import { config } from "../config/index";

@Service()
export class QiNiu {
	public FromBucket:string = config.qiniu.HLSconfig.FromBucket;
	public ToBucket:string = config.qiniu.HLSconfig.ToBucket;
	public VideoHlsParams:string = config.qiniu.HLSconfig.VideoHlsParams;
	
	public accessKey:string = config.qiniu.accessKey;
	public secretKey:string = config.qiniu.secretKey;
	// 鉴权对象mac
	public mac:any;
	
	constructor () {
		this.mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey)
	}
	
	/**
	 *
	 * @param BucketName
	 * @constructor
	 */
	public GenerateToken (BucketName:string = "vrcource"): string {
		
		let putPolicy = new qiniu.rs.PutPolicy({
			scope: BucketName,
			expires: 7200
		});
		
		return putPolicy.uploadToken(this.mac);
	}
	
	/**
	 * 根据前端传递的 filename 文件名，对需要的视频进行切片配置，
	 * 返回给前端 token，前端拿到 token 后通过form data将视频和
	 * token 传递给七牛，七牛会根据token开始切片任务。这里不需要
	 * 配置七牛切片成功后的回调通知，因为已经可以通过基地址+m3u8文件名拿到
	 * 切片后的地址
	 * @param params
	 * @constructor
	 */
	public GenerateHlsToken (params:Object): Object {
		
		let M3u8FileName = new Date().getTime();
		let saveHlsEntry = qiniu.util.urlsafeBase64Encode(`${this.ToBucket}:${M3u8FileName}`);
		
		
		const options = {
			scope: `${this.FromBucket}:${params['filename']}`,
			persistentOps: `${this.VideoHlsParams}${saveHlsEntry}`,
			persistentPipeline: 'guaikem3u8', // 多媒体处理队列名称，必填
		};
		
		let putPolicy = new qiniu.rs.PutPolicy(options);
		return {
			filePath: `${config.qiniu.HLSconfig.VideoBaseUrl}${M3u8FileName}`,
			token: putPolicy.uploadToken(this.mac)
		};
	}
	
}